<?php
    /*
     * @author Alexander.Chajka
     */

    class user {
        private $id;
        private $email;
        private $pass;
        private $token;

        public function __construct($options) {
            if (isset($_COOKIE['token']) || isset($_SESSION['token'])) {
                $this->token = $_COOKIE['token'] ? $_COOKIE['token'] : $_SESSION['token'];
                $this->login();
                
                return $this->token;
            } else {
                $this->create();
                return $this->token;
            }
        }

        private function create() {
            global $dbo;

            $expired = time() + 85600;
            $token = md5($expired);

            setcookie('token', $token, $expired);
            $_SESSION['token'] = $token;
            $this->token = $token;
            $this->id = 0;
        }
        
        private function login() {
            global $db;
            
            $db->query("SELECT * FROM #__users WHERE token = '".$this->token."'");
            $res = $db->getObject();
            
            if ($res) {
                $this->id = $res->id;
                $this->email = $res->email;
                $this->pass = $res->pass;
            } else
                $this->create();
        }

        public function checkEmail($email) {
            global $db;

            $db->query("SELECT id FROM #__users WHERE email = '".$email."'");

            if ($db->_lastResult == -1) return $db->error();
            else return $db->getResult();
        }
        
        public function register($email, $pass, $token) {
            global $db;

            $res = $db->query("INSERT INTO #__users (email, pass, token) VALUES ('$email', '".md5($pass)."', '$token')");
            if ($res) {
                $this->login();
                return 'success';
            } else
                return $db->error();
        }
    }
?>
